/**
 * @Title: http.js
 * @Description: http
 * @author: Fanchao
 * @date: 2020/9/19 3:25 下午
 * @version V1.0
 */

import axios from 'axios';
import { message } from 'antd';
import storageUtils from 'utils/storage';

axios.defaults.baseURL = process.env.baseURL;

class httpRequest {
    baseOptions(params, method = 'GET') {
        const token = storageUtils.getToken();
        axios.defaults.headers['token'] = token
        let { url, data } = params;
        // data.accessToken = accessToken;
        let contentType = 'application/json';
        contentType = params.contentType || contentType;
        let responseType = 'json';
        responseType = params.responseType || responseType;
        let option = {
            url,
            method,
            header: {
                'headers': token,
                'content-type': contentType,
            },
            responseType,
        };
        if (method === 'GET') {
            option.params = data;
        } else {
            option.data = data;
        }
        return new Promise((resolve, reject) => {
            let promise = axios.request(option);
            promise.then(response => {
                const { status, message: msg } = response;
                if (status === 200 || status === 201) {
                    resolve(response.data);
                } else {
                    message.error(msg);
                }
                // 返回正常数据
            }).catch(error => { // 失败 不调用reject 而是提示异常信息
                message.error(`请求出错了:${error}`);
            });

        });
    }

    get(url, data = '') {
        let option = { url, data };
        return this.baseOptions(option);
    }

    post(url, data, contentType, responseType) {
        let params = { url, data, contentType, responseType };
        return this.baseOptions(params, 'POST');
    }

    put(url, data = '') {
        let option = { url, data };
        return this.baseOptions(option, 'PUT');
    }

    delete(url, data = '') {
        let option = { url, data };
        return this.baseOptions(option, 'DELETE');
    }

}

export default new httpRequest();
